package com.zyw.dev.zyw.ui.fragment;

import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import com.zyw.dev.zyw.R;
import com.zyw.dev.zyw.dao.ZJWBeans;
import com.zyw.dev.zyw.utils.SMSTools;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.listener.LineChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.ChartData;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link ZJWChartFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ZJWChartFragment extends Fragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public static final String SMS_DATA_LIST = "data_list";

    private List<ZJWBeans> zjwBeansList;

    private View contentView;

    private LinearLayout ll_choice_items;

    private Button btn_density, btn_wind, btn_light, btn_temp_rh, btn_temp;

    private int chartIndex = 0;

    private float maxPointValue = 0f;

    private RadioGroup rg_radio_group;

    private String chartTitle = "正己烷浓度",xTitle = "日期";

//    private OnFragmentInteractionListener mListener;

    public ZJWChartFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment ZJWChartFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ZJWChartFragment newInstance(List<ZJWBeans> zjwBeansList) {
        ZJWChartFragment fragment = new ZJWChartFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(SMS_DATA_LIST, (Serializable) zjwBeansList);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            zjwBeansList = (List<ZJWBeans>) getArguments().getSerializable(SMS_DATA_LIST);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        contentView = inflater.inflate(R.layout.fragment_zjwchart, container, false);

        initView();
        return contentView;
    }

    private void initView() {
        ll_choice_items = (LinearLayout) contentView.findViewById(R.id.ll_choice_items);
        rg_radio_group = (RadioGroup) contentView.findViewById(R.id.rg_radio_group);

        rg_radio_group.setOnCheckedChangeListener(this);
//        btn_density = (Button) contentView.findViewById(R.id.btn_density);
//        btn_wind = (Button) contentView.findViewById(R.id.btn_wind);
//        btn_light = (Button) contentView.findViewById(R.id.btn_light);
//        btn_temp_rh = (Button) contentView.findViewById(R.id.btn_temp_rh);
//        btn_temp = (Button) contentView.findViewById(R.id.btn_temp);

//        btn_density.setOnClickListener(this);
//        btn_wind.setOnClickListener(this);
//        btn_light.setOnClickListener(this);
//        btn_temp_rh.setOnClickListener(this);
//        btn_temp.setOnClickListener(this);

        initChart();

    }

    private void generateValues() {
        maxPointValue = 0;
        for (int i = 0; i < zjwBeansList.size(); ++i) {
            Float value = 0f;
            ZJWBeans zjwBeans = zjwBeansList.get(zjwBeansList.size()-i-1);
            String valueString = "";
            switch (chartIndex){
                case 0:
                    valueString = zjwBeans.getDensity();
                    break;
                case 1:
                    valueString = zjwBeans.getWind();
                    break;
                case 2:
                    valueString = zjwBeans.getLight();
                    break;
                case 3:
                    valueString = zjwBeans.getTempRH();
                    break;
                case 4:
                    valueString = zjwBeans.getTemp();
                    break;
            }

            try{
                value = Float.parseFloat(valueString);
            }catch (Exception e){
                Log.e("Tag","数据转换错误.");
                value = 0f;
            }
            if (value>maxPointValue){
                maxPointValue = value;
            }
            randomNumbersTab[0][i] = value;
        }

        if (0 == maxPointValue){
            maxPointValue = 10f;
        }
    }

    private void generateData() {
        List<Line> lines = new ArrayList<Line>();

        for (int i = 0; i < numberOfLines; ++i) {

            List<PointValue> values = new ArrayList<PointValue>();
            for (int j = 0; j < numberOfPoints; ++j) {
                values.add(new PointValue(j, randomNumbersTab[i][j]));
                String value = SMSTools.getDataFormat(zjwBeansList.get(j).getDate());
                mAxisValueList.add(new AxisValue(j).setLabel(value));
            }

            Line line = new Line(values);
            line.setColor(ChartUtils.COLORS[i]);
            line.setShape(shape);
            line.setCubic(isCubic);
            line.setFilled(isFilled);
            line.setHasLabels(hasLabels);
            line.setHasLabelsOnlyForSelected(hasLabelForSelected);
            line.setHasLines(hasLines);
            line.setHasPoints(hasPoints);
            if (pointsHaveDifferentColor) {
                line.setPointColor(ChartUtils.COLORS[(i + 1) % ChartUtils.COLORS.length]);
            }
            lines.add(line);
        }

        data = new LineChartData(lines);

        if (hasAxes) {
            Axis axisX = new Axis();
            axisX.setValues(mAxisValueList);
            Axis axisY = new Axis().setHasLines(true);
            if (hasAxesNames) {
                axisX.setName(chartTitle);
//                axisY.setName(" ");
            }
            data.setAxisXBottom(axisX);
            data.setAxisYLeft(axisY);
        } else {
            data.setAxisXBottom(null);
            data.setAxisYLeft(null);
        }

        data.setBaseValue(Float.NEGATIVE_INFINITY);
        chart.setLineChartData(data);
    }

    private LineChartView chart;
    private LineChartData data;
    private int numberOfLines = 1;
    private int maxNumberOfLines = 1;
    private float numberOfPoints = 100.0f;
    List<AxisValue> mAxisValueList = new ArrayList<>();
    float[][] randomNumbersTab;

    private boolean hasAxes = true;
    private boolean hasAxesNames = true;
    private boolean hasLines = true;
    private boolean hasPoints = true;
    private ValueShape shape = ValueShape.CIRCLE;
    private boolean isFilled = false;
    private boolean hasLabels = true;
    private boolean isCubic = true;
    private boolean hasLabelForSelected = false;
    private boolean pointsHaveDifferentColor;

    private void initChart() {
        chart = (LineChartView) contentView.findViewById(R.id.chart);
        numberOfPoints = zjwBeansList.size();

        randomNumbersTab = new float[maxNumberOfLines][(int)numberOfPoints];
        generateValues();

        generateData();

        chart.setViewportCalculationEnabled(false);

        chart.setInteractive(true);

        Viewport v = new Viewport(0, maxPointValue+10, numberOfPoints, 0);

        chart.setMaximumViewport(v);
        chart.setCurrentViewport(v);

        chart.setZoomLevel(0, 0, numberOfPoints/8.0f);

        chart.setZoomType(ZoomType.HORIZONTAL);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    private void showChart() {
        initChart();
    }

    @Override
    public void onClick(View v) {
        showChart();
    }

    public boolean goBack() {
        if (ll_choice_items.getVisibility() == View.VISIBLE){
            return true;
        }
        ll_choice_items.setVisibility(View.VISIBLE);
        return false;
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.rb_density:
                chartIndex = 0;
                chartTitle = getString(R.string.com_zjw_density);
                break;
            case R.id.rb_wind:
                chartIndex = 1;
                chartTitle = getString(R.string.com_zjw_wind);
                break;
            case R.id.rb_light:
                chartIndex = 2;
                chartTitle = getString(R.string.com_zjw_light);
                break;
            case R.id.rb_temp_rh:
                chartIndex = 3;
                chartTitle = getString(R.string.com_zjw_humidity);
                break;
            case R.id.rb_temp:
                chartIndex = 4;
                chartTitle = getString(R.string.com_zjw_temp);
                break;
        }

        showChart();
    }

    public void setZJWBeanList(List<ZJWBeans> beanList) {
        this.zjwBeansList = zjwBeansList;
        showChart();
    }
}
